package main

import (
	"log"
	"sync/atomic"
	"time"
	"timerhelper/timer_helper"
)

func main() {
	log.SetFlags(log.Lshortfile | log.Lmicroseconds)
	log.Println("kaishi")
	// test()
	// test1()
	// test2()
	test3()
	var i = 0
	for {
		// fmt.Println(i)
		i += 1
		time.Sleep(time.Second)
	}
}

func test3() {
	th := timer_helper.Instance()
	var a = atomic.Int64{}
	for i := 0; i < 30000; i++ {
		go func(i int) {
			th.AddTicker(2, func() {
				a.Add(1)
			})
		}(i)
	}
	// for i := 0; i < 100000; i++ {
	// 	go func(i int) {
	// 		t := time.NewTicker(time.Second * 2)
	// 		for {
	// 			select {
	// 			case <-t.C:
	// 				a.Add(1)
	// 			}
	// 		}
	// 	}(i)
	// }
	th.AddTicker(1, func() {
		log.Println("-----", a.Load())
	})

	// time.Sleep(time.Millisecond * 2500)
	// log.Println("remove ticker 1001", th.Remove(1001))

	log.Println("add timeout")
	th.AddTimeout(3, func() {
		log.Println("timeout called")
	})
}

func test2() {
	th := timer_helper.Instance()
	th.AddTicker(int(time.Second*5/time.Second), func() {
		log.Println("1--------")
		// time.Sleep(time.Second * 3)
		// log.Println("2--------")
	})
}

func test1() {
	th := timer_helper.Instance()
	var i = 0
	var id int
	id = th.AddTicker(3, func() {
		i += 1
		if i > 10 {
			log.Println(th.Remove(id))
		}
		log.Println("3-ticker----")
	})
	go func() {
		var i = 0
		for ; i < 10; i++ {
			th.AddTimeout(i+1, func() {
				log.Println("----")
			})
		}
	}()
	go func() {
		var i = 0
		for ; i < 100; i++ {
			th.AddTimeout(4, func() {
				log.Println("44----")
			})
		}
	}()
	log.Println("sleep 20")
	time.Sleep(time.Second * 20)
	log.Println("sleep end ------------------------------------------------")
	go func() {
		var i = 0
		for ; i < 10; i++ {
			th.AddTimeout(i+1, func() {
				log.Println("----")
			})
		}
	}()
	go func() {
		var i = 0
		for ; i < 100; i++ {
			th.AddTimeout(4, func() {
				log.Println("44----")
			})
		}
	}()
}

func test() {
	th := timer_helper.Instance()

	id := th.AddTimeout(5, func() {
		log.Println("5-----")
	})
	log.Println(id)
	// time.Sleep(time.Second)
	log.Println("remove 5 ", th.Remove(id))
	th.AddTimeout(4, func() {
		log.Println("4-----")
	})
	th.AddTimeout(3, func() {
		log.Println("3-----")
	})
	th.AddTimeout(6, func() {
		log.Println("6-----")
	})

	id = th.AddTicker(3, func() {
		log.Println("========")
	})
	go func() {
		time.Sleep(10 * time.Second)
		log.Println("remove ticker", th.Remove(id))
		log.Println("remove ticker", th.Remove(id))
		log.Println("remove ticker", th.Remove(id))

		time.Sleep(time.Second * 5)
		log.Println("-------------------------------------------------")
		th.AddTicker(10, func() {
			log.Println("1========")
		})
	}()
}
